<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>函数、事件和对象</title>
    <style>
        table {
            border: 1px solid black;
            margin: auto;
            border-collapse: collapse;
            width: 60%;
        }

        th, td {
            border: 1px solid black;
        }
    </style>
</head>
<body>
<form action="5.html" method="get">
    <table>
        <tr>
            <th style="width: 20%">账号*</th>
            <td style="width: 40%"><input type="text" id="username"/></td>
            <td><label id="l1"></label></td>
        </tr>
        <tr>
            <th>密码*</th>
            <td><input type="password" id="password1"/></td>
            <td><span id="s2"></span></td>
        </tr>
        <tr>
            <th>确认密码*</th>
            <td><input type="password" id="password2"/></td>
            <td><span id="s3"></span></td>
        </tr>
        <tr>
            <th colspan="3">
                <button onclick="return reg()">注册</button>
            </th>
        </tr>
    </table>

</form>
</body>
</html>
<script>
    function reg() {
        // 1. 获取到三个文本框
        let usernameObj = document.getElementById('username');
        let password1Obj = document.getElementById('password1');
        let password2Obj = document.getElementById('password2');
        // 1.1 获取到三个label
        let l1Obj = document.getElementById('l1');
        let s2Obj = document.getElementById('s2');
        let s3Obj = document.getElementById('s3');
        // 2. 分别获取它们的值
        let usernameVal = usernameObj.value;
        let password1Val = password1Obj.value;
        let password2Val = password2Obj.value;
        // 3. 校验
        // 3.1 校验账号不能为空
        if (usernameVal === '') {
            // 在l1位置输出错误信息
            l1Obj.innerHTML = '账号不能为空';
            return false; // 阻止表单提交
        }
        l1Obj.innerHTML = '';
        // 3.2 校验密码不能为空
        if (password1Val === '') {
            // 在s2位置输出错误信息
            s2Obj.innerHTML = '密码不能为空';
            return false; // 阻止表单提交
        }
        s2Obj.innerHTML = '';
        if (password2Val === '') {
            s3Obj.innerHTML = '密码不能为空';
            return false;    // 阻止表单提交
        }
        s3Obj.innerHTML = '';
        // 3.3 校验密码和确认密码是否一致
        if (password1Val !== password2Val) {
            s3Obj.innerHTML = '密码不一致';
            return false;    // 阻止表单提交
        }
        s3Obj.innerHTML = '';
    }
</script>